package com.android.pantryshopping;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.pantryshopping.adapter.AddShopListAdapter;
import com.android.pantryshopping.adapter.ShopListAdapter;
import com.android.pantryshopping.bean.Commodity;
import com.android.pantryshopping.bean.ShopList;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;


import java.util.ArrayList;
import java.util.List;

public class DashboardFragment extends Fragment implements AddShopListAdapter.onCommodityItemListener, ShopListAdapter.onShopListItemListener {

    private static final String TAG = "DashboardFragment";

    private CommoditySqLiteHelper mCommoditySqLiteHelper;

    private FloatingActionButton mFloatingActionButtonAdd;
    private FloatingActionButton mFloatingActionButtonDelete;
    private RecyclerView mRecyclerView;

    private AddShopListAdapter mAddShopListAdapter;
    private ShopListAdapter mShopListAdapter;
    private ArrayList<Commodity> mCommodities;
    private ArrayList<ShopList> mShopLists;
    private ArrayList<Integer> mCheckDeleteList;
    private ArrayList<Integer> mCheckShopDeleteList;
    private RecyclerView mShopRecyclerView;
    private EditText mEdtId;
    private EditText mEdtName;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        initView(root);
        initData();
        initListener();
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mShopListAdapter != null && mCommoditySqLiteHelper != null) {
            mShopLists.clear();
            mShopLists.addAll(mCommoditySqLiteHelper.queryAllShopListData());
            mShopListAdapter.notifyDataSetChanged();
        }
    }

    private void initListener() {
        mFloatingActionButtonAdd.setOnClickListener(v -> {
            View shopListView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_add_shop_list,null);
            mShopRecyclerView = shopListView.findViewById(R.id.add_shop_rv);
            mEdtId = shopListView.findViewById(R.id.edt_id);
            mEdtName = shopListView.findViewById(R.id.edt_name);

            LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
            layoutManager.setOrientation(RecyclerView.VERTICAL);
            mShopRecyclerView.setLayoutManager(layoutManager);
            mAddShopListAdapter = new AddShopListAdapter(requireContext());
            mAddShopListAdapter.setOnCommodityItemListener(this);
            mAddShopListAdapter.setCommodities(mCommodities);
            mAddShopListAdapter.setCheckDelete(mCheckDeleteList);
            mShopRecyclerView.setAdapter(mAddShopListAdapter);
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle("Add Shopping List");
            dialog.setView(shopListView);
            dialog.setPositiveButton("Determine", (dialog1, which) -> {
                ShopList shopList = new ShopList();
                shopList.setId(mEdtId.getText().toString().trim());
                shopList.setName(mEdtName.getText().toString().trim());
                int total = 0;
                for (int i = 0; i < mCommodities.size(); i++) {
                    Commodity commodity = mCommodities.get(i);
                    String price = commodity.getPrice();
                    if (mCheckDeleteList.contains(i)) {
                        int priceNumTotal = Integer.parseInt(price);
                        total += priceNumTotal;
                    }
                }
                Gson gson = new Gson();
                String mCheckList = gson.toJson(mCheckDeleteList);
                shopList.setCommodityList(total);
                shopList.setCheckList(mCheckList);
                boolean isSuccess = mCommoditySqLiteHelper.addShopListData(shopList);
                Toast.makeText(requireContext(),isSuccess ? "Add Success" : "Add Fail",Toast.LENGTH_SHORT).show();
                dialog1.dismiss();

                mShopLists.clear();
                mShopLists.addAll(mCommoditySqLiteHelper.queryAllShopListData());
                mShopListAdapter.notifyDataSetChanged();
            });
            dialog.setNegativeButton("Cancel",null);
            dialog.create();
            dialog.show();
        });

        mFloatingActionButtonDelete.setOnClickListener(v -> {
            for (int i = 0; i < mShopLists.size(); i++) {
                Integer deleteIndex = mCheckShopDeleteList.get(i);
                ShopList shopList = mShopLists.get(deleteIndex);
                mCommoditySqLiteHelper.deleteShopListData(shopList);
            }
            mShopLists.clear();
            mShopLists.addAll(mCommoditySqLiteHelper.queryAllShopListData());
            mShopListAdapter.notifyDataSetChanged();
        });
    }

    private void initData() {
        mCommoditySqLiteHelper = new CommoditySqLiteHelper(requireContext(),"Commodity_db",null,1);
        mCommodities = new ArrayList<>();
        mShopLists = new ArrayList<>();
        mCheckDeleteList = new ArrayList<>();
        mCheckShopDeleteList = new ArrayList<>();

        List<Commodity> commodities = mCommoditySqLiteHelper.queryAllCommodityData();
        List<ShopList> shopLists = mCommoditySqLiteHelper.queryAllShopListData();
        mCommodities.addAll(commodities);
        mShopLists.addAll(shopLists);

        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mShopListAdapter = new ShopListAdapter(requireContext());
        mShopListAdapter.setOnCommodityItemListener(this);
        mShopListAdapter.setShopLists(mShopLists);
        mShopListAdapter.setCheckDelete(mCheckShopDeleteList);
        mRecyclerView.setAdapter(mShopListAdapter);
    }

    private void initView(View root) {
        mRecyclerView = root.findViewById(R.id.recyclerview);
        mFloatingActionButtonAdd = root.findViewById(R.id.flo_add);
        mFloatingActionButtonDelete = root.findViewById(R.id.flo_delete);
    }

    @Override
    public void onCommodityClick(int position) {
        Intent intent = new Intent(requireContext(),DetailsActivity.class);
        intent.putExtra("position",position);
        intent.putExtra("isShopList",false);
        startActivity(intent);
    }

    @Override
    public void onCheckDelete(int position) {
        mCheckDeleteList.add(position);
    }

    @Override
    public void onRemoveCheckDelete(int position) {
        mCheckDeleteList.remove(position);
    }

    @Override
    public void onShopClick(int position) {

        Intent intent = new Intent(requireContext(),ShopListDetailsActivity.class);
        intent.putExtra("position",position);
        startActivity(intent);
    }

    @Override
    public void onCheckShopDelete(int position) {
        mCheckShopDeleteList.add(position);
        Log.d(TAG,"onCheckShopDelete-mCheckDeleteList-->"+mCheckShopDeleteList);

    }

    @Override
    public void onRemoveShopCheckDelete(int position) {
        mCheckShopDeleteList.remove(position);
        Log.d(TAG,"onRemoveShopCheckDelete-mCheckDeleteList-->"+mCheckShopDeleteList);

    }
}